// index.js
const mybehavior = require("../../../../behaviors/requests")
// import {
//   widgetList
// } from "./test"
Page({
  behaviors: [mybehavior],
  data: {
    widgetList: [
      {
        "type": "input",
        "icon": "text-field",
        "formItemFlag": true,
        "options": {
          "name": "input57417",
          "label": "输入框1",
          "labelAlign": "",
          "type": "text",
          "defaultValue": "",
          "placeholder": "请输入",
          "columnWidth": "200px",
          "size": "",
          "labelWidth": null,
          "labelHidden": false,
          "readonly": false,
          "disabled": false,
          "hidden": false,
          "clearable": true,
          "showPassword": false,
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": [],
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "minLength": null,
          "maxLength": null,
          "showWordLimit": false,
          "prefixIcon": "",
          "suffixIcon": "",
          "appendButton": false,
          "appendButtonDisabled": false,
          "buttonIcon": "el-icon-search",
          "onCreated": "",
          "onMounted": "",
          "onInput": "",
          "onChange": "",
          "onFocus": "",
          "onBlur": "",
          "onValidate": "",
          "onAppendButtonClick": ""
        },
        "id": "test_input"
      },
      {
        "type": "textarea",
        "icon": "textarea-field",
        "formItemFlag": true,
        "options": {
          "name": "textarea109239",
          "label": "textarea",
          "labelAlign": "",
          "rows": 3,
          "defaultValue": "",
          "placeholder": "",
          "columnWidth": "200px",
          "size": "",
          "labelWidth": null,
          "labelHidden": false,
          "readonly": false,
          "disabled": false,
          "hidden": false,
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "minLength": null,
          "maxLength": null,
          "showWordLimit": false,
          "onCreated": "",
          "onMounted": "",
          "onInput": "",
          "onChange": "",
          "onFocus": "",
          "onBlur": "",
          "onValidate": ""
        },
        "id": "textarea109239"
      },
      {
        "type": "number",
        "icon": "number-field",
        "formItemFlag": true,
        "options": {
          "name": "number60756",
          "label": "number",
          "labelAlign": "",
          "defaultValue": 0,
          "placeholder": "",
          "columnWidth": "200px",
          "size": "",
          "labelWidth": null,
          "labelHidden": false,
          "disabled": false,
          "hidden": false,
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "min": -100000000000,
          "max": 100000000000,
          "precision": 0,
          "step": 1,
          "controlsPosition": "right",
          "onCreated": "",
          "onMounted": "",
          "onChange": "",
          "onFocus": "",
          "onBlur": "",
          "onValidate": ""
        },
        "id": "number60756"
      },
      {
        "type": "radio",
        "icon": "radio-field",
        "formItemFlag": true,
        "options": {
          "name": "radio74888",
          "label": "radio",
          "labelAlign": "",
          "defaultValue": null,
          "columnWidth": "200px",
          "size": "",
          "displayStyle": "inline",
          "buttonStyle": false,
          "border": false,
          "labelWidth": null,
          "labelHidden": false,
          "disabled": false,
          "hidden": false,
          "optionItems": [{
            "label": "radio 1",
            "value": 1
          },
          {
            "label": "radio 2",
            "value": 2
          },

          ],
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "onCreated": "",
          "onMounted": "",
          "onChange": "",
          "onValidate": ""
        },
        "id": "radio74888"
      },
      {
        "type": "checkbox",
        "icon": "checkbox-field",
        "formItemFlag": true,
        "options": {
          "name": "checkbox103926",
          "label": "checkbox",
          "labelAlign": "",
          "defaultValue": [],
          "columnWidth": "200px",
          "size": "",
          "displayStyle": "inline",
          "buttonStyle": false,
          "border": false,
          "labelWidth": null,
          "labelHidden": false,
          "disabled": false,
          "hidden": false,
          "optionItems": [{
            "label": "check 1",
            "value": 1
          },
          {
            "label": "check 2",
            "value": 2
          },

          ],
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "onCreated": "",
          "onMounted": "",
          "onChange": "",
          "onValidate": ""
        },
        "id": "checkbox103926"
      },
      {
        "type": "select",
        "icon": "select-field",
        "formItemFlag": true,
        "options": {
          "name": "select99349",
          "label": "select",
          "labelAlign": "",
          "defaultValue": "",
          "placeholder": "",
          "columnWidth": "200px",
          "size": "",
          "labelWidth": null,
          "labelHidden": false,
          "disabled": false,
          "hidden": false,
          "clearable": true,
          "filterable": false,
          "allowCreate": false,
          "remote": false,
          "automaticDropdown": false,
          "multiple": false,
          "multipleLimit": 0,
          "optionItems": [{
            "label": "select 1",
            "value": 1
          },
          {
            "label": "select 2",
            "value": 2
          },
          {
            "label": "select 3",
            "value": 3
          }
          ],
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "onCreated": "",
          "onMounted": "",
          "onRemoteQuery": "",
          "onChange": "",
          "onFocus": "",
          "onBlur": "",
          "onValidate": ""
        },
        "id": "select99349"
      },
      {
        "type": "select",
        "icon": "select-field",
        "formItemFlag": true,
        "options": {
          "name": "xxx",
          "label": "select2",
          "labelAlign": "",
          "defaultValue": "",
          "placeholder": "",
          "columnWidth": "200px",
          "size": "",
          "labelWidth": null,
          "labelHidden": false,
          "disabled": false,
          "hidden": false,
          "clearable": true,
          "filterable": false,
          "allowCreate": false,
          "remote": false,
          "automaticDropdown": false,
          "multiple": false,
          "multipleLimit": 0,
          "optionItems": [{
            "label": "select 1",
            "value": 1
          },
          {
            "label": "select 2",
            "value": 2
          },
          {
            "label": "select 3",
            "value": 3
          }
          ],
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "onCreated": "",
          "onMounted": "",
          "onRemoteQuery": "",
          "onChange": "",
          "onFocus": "",
          "onBlur": "",
          "onValidate": ""
        },
        "id": "select99349"
      },
      {
        "type": "date",
        "icon": "date-field",
        "formItemFlag": true,
        "options": {
          "name": "date66401",
          "label": "date",
          "labelAlign": "",
          "type": "date",
          "defaultValue": null,
          "placeholder": "",
          "columnWidth": "200px",
          "size": "",
          "labelWidth": null,
          "labelHidden": false,
          "readonly": false,
          "disabled": false,
          "hidden": false,
          "clearable": true,
          "editable": false,
          "format": "yyyy-MM-dd",
          "valueFormat": "yyyy-MM-dd",
          "required": true,
          "requiredHint": "",
          "validation": "",
          "validationHint": "",
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "onCreated": "",
          "onMounted": "",
          "onChange": "",
          "onFocus": "",
          "onBlur": "",
          "onValidate": ""
        },
        "id": "date66401"
      },

      {
        "type": "switch",
        "icon": "switch-field",
        "formItemFlag": true,
        "options": {
          "name": "switch59262",
          "label": "switch",
          "labelAlign": "",
          "defaultValue": false,
          "columnWidth": "200px",
          "labelWidth": null,
          "labelHidden": false,
          "disabled": false,
          "hidden": false,
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "switchWidth": 40,
          "activeText": "",
          "inactiveText": "",
          "activeColor": null,
          "inactiveColor": null,
          "onCreated": "",
          "onMounted": "",
          "onChange": "",
          "onValidate": ""
        },
        "id": "switch59262"
      },
      {
        "type": "picture-upload",
        "icon": "picture-upload-field",
        "formItemFlag": true,
        "options": {
          "name": "pictureupload32596",
          "label": "picture-upload",
          "labelAlign": "",
          "labelWidth": null,
          "labelHidden": false,
          "columnWidth": "200px",
          "disabled": false,
          "hidden": false,
          "required": true,
          "requiredHint": "",
          "customRule": "",
          "customRuleHint": "",
          "uploadURL": "https://logisticsengineering.gree.com/container_manage_api/container_manage",
          "uploadTip": "",
          "withCredentials": false,
          "multipleSelect": false,
          "showFileList": true,
          "limit": 3,
          "fileMaxSize": 5,
          "fileTypes": ["jpg", "jpeg", "png"],
          "customClass": "",
          "labelIconClass": null,
          "labelIconPosition": "rear",
          "labelTooltip": null,
          "onCreated": "",
          "onMounted": "",
          "onBeforeUpload": "",
          "onUploadSuccess": "",
          "onUploadError": "",
          "onFileRemove": "",
          "onValidate": ""
        },
        "id": "pictureupload32596"
      },


    ],
    formField: {},
    selectShow: false,
    timePickerShow: false,
    selectOptions: [],
    pickerFieldId: "",
    selectPicker: {},
    checked: false,
    choose_img_btn_disabled: false,
    popup_date_show: false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
  },
  // 检查必填项
  checkRequired() {
    let arr = this.data.widgetList
    let arr1 = this.data.formField
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].options.required == true && arr1[arr[i].options.name] == undefined) {
        wx.showToast({
          title: arr[i].options.label + '不能为空！',
          icon: 'none'
        })
        return false
      }
    }
    return true

  },
  // 提交表单数据
  submit() {
    if (this.checkRequired() == true) {
      console.log(this.data);
    }
  },
  // 重置按钮
  reset() {
    this.setData({
      formField: {},

    })
  },
  //   输入框值变化
  inputChange(e) {
    // console.log(e);
    let key = e.target.dataset.item.options.name
    let obj = JSON.parse(JSON.stringify(this.data.formField))
    obj[key] = e.detail
    this.setData({
      formField: obj
    })
  },
  // 下拉选择框弹窗显示
  handleTap(e) {
    this.setData({
      selectOptions: e.currentTarget.dataset.optionitems,
      selectShow: true,
      pickerFieldId: e.currentTarget.dataset.id
    })
  },

  // 下拉选择框弹窗关闭
  onCancel(e) {
    this.setData({
      selectShow: false
    })
  },
  // 下拉选择框值确认
  onConfirm(e) {
    let value = e.detail.value.value
    let key = this.data.pickerFieldId
    let obj = JSON.parse(JSON.stringify(this.data.formField))
    obj[key] = value
    this.setData({
      formField: obj,
    })
    this.onCancel()
  },
  // 点击输入框显示选择日期
  onDateClick(e) {
    let key = e.target.dataset.item.options.name
    this.setData({
      popup_date_show: true,
      pickerFieldId: key
    });
  },
  // 确定日期输入框
  onDateConfirm(e) {
    let obj = JSON.parse(JSON.stringify(this.data.formField))
    let val = this.formatDate1(new Date(e.detail))
    obj[this.data.pickerFieldId] = val
    this.setData({
      popup_date_show: false,
      formField: obj
    });
  },
  // 日期输入框关闭
  onDateClose() {
    this.setData({
      popup_date_show: false,
    });
  },

  // 照片选取
  try_upload(e) {
    let upload_id = e.currentTarget.dataset.item.options.name
    const self = this;
    self.setData({
      choose_img_btn_disabled: true
    })
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        wx.showLoading({
          title: '开始上传。。。',
        })

        wx.uploadFile({
          url: e.currentTarget.dataset.item.options.uploadURL + '/fs_upload',
          filePath: tempFilePath,
          name: 'file',
          formData: {
          },
          success(res) {
            const result = JSON.parse(res.data);
            wx.hideLoading();
            if (result.code == 20000) {
              let uploader = []
              if (self.data.formField[upload_id] != undefined) {
                uploader = self.data.formField[upload_id];
              }

              const new_uploader = uploader.concat({
                url: e.currentTarget.dataset.item.options.uploadURL + '/fs_download?file_id=' + result.data.file_id,
                isImage: true,
                file_id: result.data.file_id
              })

              let obj = JSON.parse(JSON.stringify(self.data.formField))
              obj[upload_id] = new_uploader
              self.setData({
                formField: obj,

              })

              if (self.data.formField[upload_id].length < 3) {
                self.setData({
                  choose_img_btn_disabled: false
                })
              }
              wx.showToast({
                title: '上传成功！',
              })
            } else {
              if (self.data.formField[upload_id].length < 3) {
                self.setData({
                  choose_img_btn_disabled: false
                })
              }
              wx.showToast({
                title: result.msg,
                icon: "error"
              })
            }

          },
          fail(res) {
            wx.hideLoading();
            if (self.data.formField[upload_id].length < 3) {
              self.setData({
                choose_img_btn_disabled: false
              })
            }
            wx.showToast({
              title: "未知错误428",
              icon: "error"
            })
          }
        })

      },
      fail() {
        if (self.data.uploader.length < 3) {
          self.setData({
            choose_img_btn_disabled: false
          })
        }
      }



    })
  },

  // 删除照片
  handle_delete(e) {
    let upload_id = e.currentTarget.dataset.item.options.name
    let img_arr = this.data.formField[upload_id]
    const index = e.detail.index;
    const file = img_arr[index];
    const file_id = file.url.split("=")[1];
    const uploader = img_arr;
    const self = this;

    let url1 = e.currentTarget.dataset.item.options.uploadURL + '/fs_delete'
    let data = {
      file_id
    }
    this.post(url1, data).then(res => {
      if (res.code == 20000) {
        wx.showToast({
          title: res.msg,
          icon: 'success'
        })

        uploader.splice(index, 1);
        self.setData({
          choose_img_btn_disabled: false,
        })

        let obj = JSON.parse(JSON.stringify(self.data.formField))
        obj[upload_id] = uploader
        if (obj[upload_id].length == 0) {
          delete obj[upload_id]
        } 
        self.setData({
          formField: obj,

        })

      } else {
        wx.showToast({
          title: res.msg,
          icon: 'error'
        })
      }
    }).catch(err => {
      console.log(err);
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  onReady() {

  }
})